package com.li.recycleradapter;

import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;

/**
 * Author: Li
 * Date: 2017/3/30
 * Description:
 */

public class HeaderFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int BASE_TYPE_HEADER = 100;
    private static final int BASE_TYPE_FOOTER = 200;

    private RecyclerView.Adapter mInnerAdapter;
    private SparseArrayCompat<View> mHeaderViews;
    private SparseArrayCompat<View> mFooterViews;


    public void setLoading(boolean loading) {
        mIsLoading = loading;
    }

    private boolean mIsLoading = false;

    /**
     * 是否加载完全
     * @param loadAll 加载全部
     */
    public void setLoadAll(boolean loadAll) {
        mLoadAll = loadAll;
    }

    private boolean mLoadAll=false;
    /**
     * 设置是否可以加载
     * @param canLoad   是否可以加载
     */
    public void setCanLoad(boolean canLoad) {
        mCanLoad = canLoad;
    }

    private boolean mCanLoad = true;


    public void setOnEdgeListener(OnEdgeListener onEdgeListener) {
        mOnEdgeListener = onEdgeListener;
    }

    private OnEdgeListener mOnEdgeListener;

    public HeaderFooterAdapter(RecyclerView.Adapter innerAdapter) {
        mHeaderViews = new SparseArrayCompat<>();
        mFooterViews = new SparseArrayCompat<>();
        mInnerAdapter = innerAdapter;
    }

    /**
     * 当前是否为头部
     *
     * @param position 位置
     * @return 结果
     */
    private boolean isHeaderViewPos(int position) {
        return position < getHeaderCount();
    }

    /**
     * 当前是否为底部
     *
     * @param position 当前位置
     * @return 结果
     */
    private boolean isFooterViewPos(int position) {
        return position >= getHeaderCount() + getRealItemCount();
    }

    public int getHeaderCount() {
        return mHeaderViews.size();
    }

    public int getRealItemCount() {
        return mInnerAdapter.getItemCount();
    }

    public int getFooterCount() {
        return mFooterViews.size();
    }

    /**
     * 添加头部
     *
     * @param view 控件
     */
    public void addHeaderView(View view) {
        mHeaderViews.put(mHeaderViews.size() + BASE_TYPE_HEADER, view);
    }

    /**
     * 添加底部
     *
     * @param view 控件
     */
    public void addFooterView(View view) {
        mFooterViews.put(mFooterViews.size() + BASE_TYPE_FOOTER, view);
    }

    @Override
    public int getItemViewType(int position) {

        if (isHeaderViewPos(position)) {
            return mHeaderViews.keyAt(position);
        } else if (isFooterViewPos(position)) {
            return mFooterViews.keyAt(position - getRealItemCount() - getHeaderCount());
        }
        return mInnerAdapter.getItemViewType(position - getHeaderCount());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (mHeaderViews.get(viewType) != null) {
            return new RecyclerView.ViewHolder(mHeaderViews.get(viewType)) {
            };

        } else if (mFooterViews.get(viewType) != null) {
            return new RecyclerView.ViewHolder(mFooterViews.get(viewType)) {
            };

        }
        return mInnerAdapter.createViewHolder(parent, viewType);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (isFooterViewPos(position) || isHeaderViewPos(position)) {
            return;
        }
        mInnerAdapter.onBindViewHolder(holder, position - getHeaderCount());
    }

    @Override
    public int getItemCount() {
        return getHeaderCount() + getFooterCount() + getRealItemCount();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    int viewType = getItemViewType(position);
                    if (mHeaderViews.get(viewType) != null || mFooterViews.get(viewType) != null) {
                        return gridLayoutManager.getSpanCount();
                    }

                    return 1;
                }
            });
        }


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(-1)) {
//                    Log.e("tag", "onScrolled: "+"到头");
                }
                /**
                 * 当可以加载时候
                 * 判断是否滚动到底部并且处于未加载状态
                 */
                if (mCanLoad) {
                    if (mLoadAll) {
                        if (mOnEdgeListener != null) {
                            mOnEdgeListener.onLoadAll();
                        }
                        return;
                    }
                    if (!recyclerView.canScrollVertically(1)
                            && !mIsLoading) {
                        if (mOnEdgeListener != null) {
                            mIsLoading=true;
                            mOnEdgeListener.onBottom();
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int position = holder.getLayoutPosition();
        /*
            当该位置是头部或底部的时候
            判断layoutManager是否为瀑布流
            如果是的话，让其占满一行

         */
        if (isHeaderViewPos(position) || isFooterViewPos(position)) {
            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();

            if (lp != null
                    && lp instanceof StaggeredGridLayoutManager.LayoutParams) {

                StaggeredGridLayoutManager.LayoutParams p =
                        (StaggeredGridLayoutManager.LayoutParams) lp;
                p.setFullSpan(true);
            }
        }
    }

    public interface OnEdgeListener {
        void onBottom();
        void onLoadAll();
    }
}
